package it.vetlab;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListinoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (authenticateUser(req) != null) {
			boolean listino2013 = "/listino2013.pdf".equals(req.getRequestURI());
			resp.setContentType("application/pdf");
			resp.setContentLength(listino2013 ? 294891 : 351350);
			ServletOutputStream out = resp.getOutputStream();

			BufferedInputStream in = null;
			try {
				in = new BufferedInputStream(getClass().getClassLoader()
						.getResourceAsStream(listino2013 ? "NEW_color_2013_LISTINO VETLAB.pdf" : "LISTINO.pdf"));
				byte[] buffer = new byte[4096];
				int length;
				while ((length = in.read(buffer)) > 0) {
					out.write(buffer, 0, length);
				}
			} finally {
				if (in != null)
					in.close();
			}
			out.flush();
		} else {
			resp.sendRedirect("/listino.jsp");
		}
	};

	private User authenticateUser(HttpServletRequest req) {
		if (req.getCookies() != null) {
			for (Cookie cookie : req.getCookies()) {
				if ("user".equals(cookie.getName())) {
					return VetLabService.getInstance().getUserByCookie(
							cookie.getValue());
				}
			}
		}
		return null;
	}

}
